package com.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 两数之和
 */
public class 两数之和 {

    public static int[] twoSum(int nums[], int target) {
        int sum = 0;
        for (int i = 1; i < nums.length; i++) {
            int j = i - 1;
            while (j >= 0) {
                sum = nums[i] + nums[j];
                if (sum == target) {
                    return new int[]{j, i};
                } else {
                    j--;
                }
            }
        }
        return new int[]{};
    }

    public static int[] twoSum1(int nums[], int target) {
        HashMap<Integer, Integer> integerIntegerHashMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (integerIntegerHashMap.containsKey(target - nums[i])) {
                return new int[]{integerIntegerHashMap.get(target - nums[i]), i};
            }
            integerIntegerHashMap.put(nums[i], i);
        }
        return new int[]{};
    }

    static List<List<Integer>> res = new ArrayList();

    public static List<List<Integer>> threeSum(int nums[]) {
        int len = nums.length;
        Arrays.sort(nums);
        for (int i = 0; i < len; i++) {
            if (nums[i] > 0) continue;
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int target = 0 - nums[i];
            int l = i + 1;
            int r = len - 1;
            while (i < r) {
                List<Integer> list = new ArrayList();
                if (nums[l] + nums[r] == target) {
                    list.add(nums[i]);
                    list.add(nums[l]);
                    list.add(nums[r]);
                    res.add(list);
                    while (r > l && nums[l] == nums[l + 1]) l++;
                    while (r > l && nums[r] == nums[r - 1]) r--;
                    l++;
                    r--;
                } else if (nums[l] + nums[r] > target) {
                    r--;
                } else {
                    l++;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{-3, 4, 3, 0, 8};
        List<List<Integer>> lists = threeSum(arr);
        String s = lists.toString();
        System.out.println(s);
    }

}
